package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.BuildConfig;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.MerchatsDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;

/**
 * Created by 朱俊鑫 on 2018
 */

public class MainMerchatsMainActivity extends AppCompatActivity {

    public final int REQUEST_CAMERA = 104;
    public final int REQUEST_CAMERA1 = 107;
    public final int REQUEST_CROP = 105;
    public final int REQUEST_CROP1 = 106;
    public final int REQUEST_IMAGECOUNT = 1031;
    public final int REQUEST_IMAGECOUNT1 = 1032;
    BottomDialog bottomDialog;
    BottomDialog bottomDialog1;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.bg_iv)
    ImageView bgIv;
    @BindView(R.id.cir_icon)
    CircleImageView cirIcon;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.camera_bt)
    RelativeLayout cameraBt;
    @BindView(R.id.merchatsmain_ty)
    TextView merchatsmainTy;
    @BindView(R.id.merchatsmain_bt)
    RelativeLayout merchatsmainBt;
    @BindView(R.id.huodong_tv)
    TextView huodongTv;
    @BindView(R.id.huodong_bt)
    RelativeLayout huodongBt;
    @BindView(R.id.content_city)
    TextView contentCity;
    @BindView(R.id.upstore_bt)
    RelativeLayout upstoreBt;
    @BindView(R.id.downstore_bt)
    RelativeLayout downstoreBt;
    MerchatsDomain domain;
    private  File temp_cmera = null;
    private Dialog loadingdialog;
    private String temppath1;
    private String temppath2;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchatsmain);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
        initQuery();
    }

    private void initComponent() {
        loadingdialog = new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.setCanceledOnTouchOutside(false);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        bottomDialog = BottomDialog.create(getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View camera = v.findViewById(R.id.camera);
                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        temp_cmera = new File(getExternalCacheDir().getAbsolutePath()+"/" + UUID.randomUUID().toString().substring(0, 10) + ".jpg");
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra("return-data", true);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(MainMerchatsMainActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider",temp_cmera);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
                        } else {
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                        }
                        startActivityForResult(intent, REQUEST_CAMERA);
                        bottomDialog.dismiss();
                    }
                });
                View exit = v.findViewById(R.id.exit);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View imgcontent = v.findViewById(R.id.imgcontent);
                imgcontent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                        intent.setType("image/*");
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, REQUEST_IMAGECOUNT);
                        bottomDialog.dismiss();
                    }
                });
            }
        });
        bottomDialog.setLayoutRes(R.layout.dialog_uploadimg);
        bottomDialog.setDimAmount(0.5f);
        bottomDialog.setCancelOutside(true);
        bottomDialog.setTag("BottomDialog");


        bottomDialog1 = BottomDialog.create(getSupportFragmentManager());
        bottomDialog1.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog1.dismiss();
                    }
                });
                View camera = v.findViewById(R.id.camera);
                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        temp_cmera = new File(getExternalCacheDir().getAbsolutePath()+"/" + UUID.randomUUID().toString().substring(0, 10) + ".jpg");
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra("return-data", true);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(MainMerchatsMainActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider",temp_cmera);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
                        } else {
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                        }
                        startActivityForResult(intent, REQUEST_CAMERA1);
                        bottomDialog1.dismiss();
                    }
                });
                View exit = v.findViewById(R.id.exit);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog1.dismiss();
                    }
                });
                View imgcontent = v.findViewById(R.id.imgcontent);
                imgcontent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                        intent.setType("image/*");
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, REQUEST_IMAGECOUNT1);
                        bottomDialog1.dismiss();
                    }
                });
            }
        });
        bottomDialog1.setLayoutRes(R.layout.dialog_uploadimg);
        bottomDialog1.setDimAmount(0.5f);
        bottomDialog1.setCancelOutside(true);
        bottomDialog1.setTag("BottomDialog");

    }

    @OnClick(value = {R.id.backbt,R.id.cir_icon,R.id.camera_bt,R.id.merchatsmain_bt,R.id.huodong_bt,R.id.upstore_bt,R.id.downstore_bt})
    public  void onMyClick(View view){
        Map<String,Object> map=new HashMap<>();
        switch (view.getId()){
            case R.id.upstore_bt:
                if(domain==null){
                    return;
                }
                   map.put("merchantsId",domain.getData().getMerchantsId());
             Tools.redirectActivity(this,UpMerchandiseActivity.class,map);
                break;
            case R.id.backbt:
                finish();
                break;
            case R.id.cir_icon:
                bottomDialog.show();
                break;
            case R.id.camera_bt:
                bottomDialog1.show();
                break;
            case R.id.merchatsmain_bt:
                if(domain==null){
                    return;
                }
                map.put("merchantsId",domain.getData().getMerchantsId());
             Tools.redirectActivity(this,MerchatsmainDynmicListActivity.class,map);
                break;
            case R.id.huodong_bt:
                Tools.redirectActivity(this,MerchantFriendCircleListActivity.class,map);
                    break;
            case R.id.downstore_bt:
                map.put("merchantsId",domain.getData().getMerchantsId());
                Tools.redirectActivity(this,DownMerchandiseActivity.class,map);
                break;
        }
    }

     public void initQuery(){
         final List<User> userList = Xutils.queryAll(getApplication(), User.class);
            if(userList==null||userList.size()==0){
                return;
            }
         Map<String,String>  map=new HashMap<>();
            map.put("userId",""+userList.get(0).getUserId());
         Xutils.POST(HttpUrl.querymainbyuseridmerchant, map, new Callback.CommonCallback<String>() {
             @Override
             public void onSuccess(String result) {
                 Gson gson=new Gson();
                 domain=gson.fromJson(result,MerchatsDomain.class);

                 switch (domain.getState()){
                     case HttpCode.SUCCESS:
                         Glide.with(MainMerchatsMainActivity.this)
                                 .load(domain.getData().getMerchantsAvatarpath())
                                 .asBitmap()
                                 .animate(R.anim.fade_in)
                                 .centerCrop()
                                 .placeholder(R.drawable.nim_avatar_default)
                                 .into(new SimpleTarget<Bitmap>() {
                                     @Override
                                     public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                       cirIcon.setImageBitmap(resource);
                                     }
                                 });
                         Glide.with(MainMerchatsMainActivity.this)
                                 .load(domain.getData().getMerchantsBgpath())
                                 .asBitmap()
                                 .centerCrop()
                                 .animate(R.anim.fade_in)
                                 .placeholder(R.drawable.nim_avatar_default)
                                 .into(new SimpleTarget<Bitmap>() {
                                     @Override
                                     public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                         bgIv.setImageBitmap(resource);
                                     }
                                 });
                     name.setText(domain.getData().getMerchantsName() + "");
                         break;
                 }
             }

             @Override
             public void onError(Throwable ex, boolean isOnCallback) {

             }

             @Override
             public void onCancelled(CancelledException cex) {

             }

             @Override
             public void onFinished() {

             }
         });
     }

     public void uploadAvator(File file){
         final List<User> userList = Xutils.queryAll(getApplication(), User.class);
         if(userList==null||userList.size()==0){
             return;
         }
         loadingdialog.show();
         Map<String,Object> map=new HashMap<>();
           map.put("files",file);
          map.put("userId",userList.get(0).getUserId()+"");
           Xutils.UpLoadFile(HttpUrl.avatarmerchant, map, new Callback.CommonCallback<String>() {
               @Override
               public void onSuccess(String result) {
                   loadingdialog.dismiss();
                   Gson gson = new Gson();
                   MerchatsDomain domain=gson.fromJson(result,MerchatsDomain.class);
                   Toast.makeText(getApplicationContext(), domain.getMessage(), Toast.LENGTH_SHORT).show();
                   switch (domain.getState()){
                       case HttpCode.SUCCESS:
                           initQuery();
                           break;
                   }

               }

               @Override
               public void onError(Throwable ex, boolean isOnCallback) {
                   loadingdialog.dismiss();
                   Toast.makeText(getApplicationContext(), "请稍后再试", Toast.LENGTH_SHORT).show();
               }

               @Override
               public void onCancelled(CancelledException cex) {

               }

               @Override
               public void onFinished() {

               }
           });
     }


    public void uploadBg(File file){
        final List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if(userList==null||userList.size()==0){
            return;
        }
        loadingdialog.show();
        Map<String,Object> map=new HashMap<>();
        map.put("files",file);
        map.put("userId",userList.get(0).getUserId()+"");
        Xutils.UpLoadFile(HttpUrl.bgmerchant, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                loadingdialog.dismiss();
                Gson gson = new Gson();
                MerchatsDomain domain=gson.fromJson(result,MerchatsDomain.class);
                Toast.makeText(getApplicationContext(), domain.getMessage(), Toast.LENGTH_SHORT).show();
                switch (domain.getState()){
                    case HttpCode.SUCCESS:
                        initQuery();
                        break;
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                loadingdialog.dismiss();
                Toast.makeText(getApplicationContext(), "请稍后再试", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Uri datauri = data.getData();
        final File finalFile1 = new File(getExternalCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString().substring(0, 10) + ".png");
        ;
        Intent bgcamera = new Intent("com.android.camera.action.CROP");
        switch (requestCode) {
            case REQUEST_IMAGECOUNT:
                Glide.with(this)
                        .load(datauri)
                        .asBitmap()
                        .override(500, 500)
                        .placeholder(getResources().getColor(R.color.default_lightgray))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                try {
                                    Bitmap bitmap = null;
                                    if (resource.getHeight() < 500) {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 1, resource.getHeight() / 1);
                                    } else if (resource.getHeight() < 1000) {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 2, resource.getHeight() / 2);
                                    } else {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 3, resource.getHeight() / 3);
                                    }
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(finalFile1));
                                    temppath1 = finalFile1.getPath();
                                    uploadAvator(finalFile1);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;

            case REQUEST_CAMERA:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    bgcamera.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(MainMerchatsMainActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", temp_cmera);
                    bgcamera.setDataAndType(contentUri, "image/*");
                } else {
                    bgcamera.setDataAndType(Uri.fromFile(temp_cmera), "image/*");
                }
                bgcamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                bgcamera.putExtra("return-data", false);
                bgcamera.putExtra("scale", true);
                bgcamera.putExtra("outputFormat", Bitmap.CompressFormat.PNG);
                bgcamera.putExtra("noFaceDetection", true);
                //     bgcamera.putExtra("aspectX",son1);
                //     bgcamera.putExtra("aspectY",son1);
                bgcamera.putExtra("outputX", 500);
                bgcamera.putExtra("outputY", 500);
                startActivityForResult(bgcamera, REQUEST_CROP);
                break;

            case REQUEST_CROP:
                Glide.with(this)
                        .load(temp_cmera.getPath())
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                Bitmap bitmap = null;
                                if (resource.getHeight() < 500) {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 1, resource.getHeight() / 1);
                                } else if (resource.getHeight() < 1000) {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 2, resource.getHeight() / 2);
                                } else {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 3, resource.getHeight() / 3);
                                }
                                try {
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(temp_cmera));
                                    temppath1 = temp_cmera.getPath();
                                    uploadAvator(temp_cmera);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;


            case REQUEST_IMAGECOUNT1:
                Glide.with(this)
                        .load(datauri)
                        .asBitmap()
                        .override(500, 500)
                        .placeholder(getResources().getColor(R.color.default_lightgray))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                try {
                                    Bitmap bitmap = null;
                                    if (resource.getHeight() < 500) {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 1, resource.getHeight() / 1);
                                    } else if (resource.getHeight() < 1000) {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 2, resource.getHeight() / 2);
                                    } else {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 3, resource.getHeight() / 3);
                                    }
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(finalFile1));
                                    temppath2 = finalFile1.getPath();
                                    uploadBg(finalFile1);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;
            case REQUEST_CAMERA1:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    bgcamera.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(MainMerchatsMainActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", temp_cmera);
                    bgcamera.setDataAndType(contentUri, "image/*");
                } else {
                    bgcamera.setDataAndType(Uri.fromFile(temp_cmera), "image/*");
                }
                bgcamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                bgcamera.putExtra("return-data", false);
                bgcamera.putExtra("scale", true);
                bgcamera.putExtra("outputFormat", Bitmap.CompressFormat.PNG);
                bgcamera.putExtra("noFaceDetection", true);
                //     bgcamera.putExtra("aspectX",son1);
                //     bgcamera.putExtra("aspectY",son1);
                bgcamera.putExtra("outputX", 500);
                bgcamera.putExtra("outputY", 500);
                startActivityForResult(bgcamera, REQUEST_CROP);
                break;

            case REQUEST_CROP1:
                Glide.with(this)
                        .load(temp_cmera.getPath())
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                Bitmap bitmap = null;
                                if (resource.getHeight() < 500) {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 1, resource.getHeight() / 1);
                                } else if (resource.getHeight() < 1000) {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 2, resource.getHeight() / 2);
                                } else {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 3, resource.getHeight() / 3);
                                }
                                try {
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(temp_cmera));
                                    temppath2 = temp_cmera.getPath();
                                    uploadBg(temp_cmera);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;
        }
    }
}
